function variance(day) {
	var i = 0;
	var diff = new Array(day.length);
	
	for (i = 20; i < day.length; i++){
		var avg = 0;
		for (var j = 0; j < 20; j++) {
			var e = day[i-j];
			avg += e.high + e.low;
		}
		avg = avg / 40;
		
		var s = 0;
		for (var j = 0; j < 20; j++) {
			var e = day[i-j];
			s += (e.high-avg)*(e.high-avg) + (e.low-avg)*(e.low-avg);
		}
		s = Math.sqrt(s / 39);
		
		diff[i] = {avg:avg,sv:s};
	}
	
	if (day.length >= 20) {
		for (i = 0; i < 20; i++) {
			diff[i] = diff[20];
		}
	}
	
	return diff;
}

function kLine(dom, stock){
	
	//console.log(stock);
	
	skip_days = stock.skip - 3;
	if (skip_days < 0) skip_days = 0;
	
	var myChart = echarts.init(dom, null, {renderer: 'svg'});
	var app = {};
	var option = null;

	var colorList = ['#c23531','#2f4554', '#61a0a8', '#d48265', '#91c7ae','#749f83',  '#ca8622', '#bda29a','#6e7074', '#546570', '#c4ccd3'];
	var labelFont = 'bold 12px Sans-serif';
	
	

	var dates = [];
	var data = [];
	var volumes = [];
	var dataMA5 = [];
	var dataMA10 = [];
	var dataMA30 = [];
	var dataHigh = [];
	var dataLow = [];
	
	/*
{
day: "2017-03-09 10:45:00",
open: "41.170",
high: "41.260",
low: "41.160",
close: "41.240",
radio : (close - open)/open,
volume: "92200",
ma_price5: 41.324,
ma_volume5: 242366,
ma_price10: 41.324,
ma_volume10: 242366,
ma_price30: 41.324,
ma_volume30: 242366
}

[open, close, lowest, highest] （即：[开盘值, 收盘值, 最低值, 最高值]）
*/
	
	var v = variance(stock.day);
	console.log(v, stock.day);
	for (var i = 0; i < stock.day.length; i++){
		var e = stock.day[i];
		
		dates.push(e.day);
		data.push([e.open, e.close, e.low, e.high]);
		
		volumes.push(e.volume || null);
		dataMA5.push(e.ma_price5 || null)
		dataMA10.push(e.ma_price10 || null)
		
		var sv = v[i];
		dataMA30.push(sv.avg)
		dataHigh.push(sv.avg + (2 * sv.sv));
		dataLow.push(sv.avg - (2 * sv.sv));
		
		/*
		if (i > 5){
			dataHigh.push(linear(stock.day.slice(i - 5, i), 'high').next);
			dataLow.push(linear(stock.day.slice(i - 5, i), 'low').next)
		}else{
			dataHigh.push(e.high);
			dataLow.push(e.low);
		}
		*/
	}
	
	
	option = {
		animation: false,
		color: colorList,
		/*
		title: {
			left: 'center',
			text: stock.id
		},
		
		legend: {
			top: 30,
			data: ['日K', 'MA5', 'MA10', 'MA30', 'High', 'Low']
		},
		*/
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'cross'
			},
			formatter: function (params, ticket, callback) {
				var id = 0;
				for (var i in params){
					var p = params[i];
					if ("candlestick" == p.seriesType){
						id = p.dataIndex;
						break;
					}
				}
				if (id <= 0) {
					return;
				}
				var out = [];
				var d = stock.day[id];
				var d1 = stock.day[id-1];
				out.push(d.day);
				out.push("价格：O,C,H,L | " + [d.open, d.close, d.high, d.low].join(", "));
				out.push("相对昨日收盘：O,C,H,L/C% | " + 
					[
					((d.open*100/d.last)-100).toFixed(2),
					((d.close*100/d.last)-100).toFixed(2),
					((d.high*100/d.last)-100).toFixed(2),
					((d.low*100/d.last)-100).toFixed(2)
					].join(", "));
				out.push("均线价：MA(C)5,10,30 | " + [d.ma_price5,d.ma_price10,d.ma_price30].join(", "));
				out.push("收盘相对均线：C/MA(C)%5,10,30 | " + 
					[
					((d.close*100/d.ma_price5)-100).toFixed(2),
					((d.close*100/d.ma_price10)-100).toFixed(2),
					((d.close*100/d.ma_price30)-100).toFixed(2)
					].join(", "));
				out.push("量相对均线：V/MA(V)5,10,30 | " + 
					[
					((d.volume/d.ma_volume5)).toFixed(2),
					((d.volume/d.ma_volume10)).toFixed(2),
					((d.volume/d.ma_volume30)).toFixed(2)
					].join(", "));
				var sv = v[id];
				var sv1 = v[id-1];
				out.push("方差范围：-SV+ W | " + 
					[
					(sv.avg - (2 * sv.sv)).toFixed(2),
					(sv.avg + 0.0).toFixed(2),
					(sv.avg + (2 * sv.sv)).toFixed(2),
					(1 * sv.sv * 100/sv.avg).toFixed(2),
					(2 * sv.sv * 100/sv.avg).toFixed(2)
					].join(", "));
					
				var avgR = ((sv.avg - sv1.avg)*100/sv.avg);
				var highR = ((sv.avg + (2 * sv.sv) - sv1.avg - (2 * sv1.sv))*100/sv.avg);
				var lowR = ((sv.avg - (2 * sv.sv) - sv1.avg + (2 * sv1.sv))*100/sv.avg);
				out.push("斜率：均值,方差+- | " + 
					[
					avgR.toFixed(2),highR.toFixed(2),lowR.toFixed(2)
					].join(", "));
				var state = 0;
				if ((avgR > 0) && (highR > avgR)) {
					state = 1;
				} else if ((avgR < 0) && (lowR < avgR)) {
					state = -1;
				} else {
					state = 0;
				}
				out.push("买卖：多空| " + 
					[
						state
					].join(", "));
				return out.join("<br/>");
			},
			position: function (pos, params, el, elRect, size) {
				var obj = {
					top: 30
				};
				obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 5;
				return obj;
			}
		},
		axisPointer: {
			link: [{
				xAxisIndex: [0, 1]
			}]
		},
		dataZoom: [{
			type: 'slider',
			xAxisIndex: [0, 1],
			realtime: false,
			startValue: stock.day.length - 80 - skip_days,
			endValue : stock.day.length - 1 - skip_days,
			top: 10,
			height: 20,
			handleIcon: 'M10.7,11.9H9.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4h1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
			handleSize: '120%'
		}/*, {
			type: 'inside',
			xAxisIndex: [0, 1],
			start: 80,
			end: 100,
			top: 30,
			height: 20
		}*/],
		xAxis: [{
			type: 'category',
			data: dates,
			boundaryGap : false,
			axisLine: { lineStyle: { color: '#777' } },
			axisLabel: {
				formatter: function (value) {
					return echarts.format.formatTime('MM-dd', value);
				}
			},
			min: 'dataMin',
			max: 'dataMax',
			axisPointer: {
				show: true
			}
		}, {
			type: 'category',
			gridIndex: 1,
			data: dates,
			scale: true,
			boundaryGap : false,
			splitLine: {show: false},
			axisLabel: {show: false},
			axisTick: {show: false},
			axisLine: { lineStyle: { color: '#777' } },
			splitNumber: 20,
			min: 'dataMin',
			max: 'dataMax',
			axisPointer: {
				type: 'shadow',
				label: {show: false},
				triggerTooltip: true,
				handle: {
					show: true,
					margin: 30,
					color: '#B80C00'
				}
			}
		}],
		yAxis: [{
			scale: true,
			splitNumber: 2,
			axisLine: { lineStyle: { color: '#777' } },
			splitLine: { show: true },
			axisTick: { show: false },
			axisLabel: {
				inside: true,
				formatter: '{value}\n'
			}
		}, {
			scale: true,
			gridIndex: 1,
			splitNumber: 2,
			axisLabel: {show: false},
			axisLine: {show: false},
			axisTick: {show: false},
			splitLine: {show: false}
		}],
		grid: [{
			left: 10,
			right: 10,
			top: 50,
			height: 180
		}, {
			left: 10,
			right: 10,
			height: 80,
			top: 260
		}],
		graphic: [{
			type: 'group',
			left: 'center',
			top: 35,
			width: 300,
			bounding: 'raw',
			children: [{
				id: 'MA5',
				type: 'text',
				style: {fill: colorList[1], font: labelFont},
				left: 0
			}, {
				id: 'MA10',
				type: 'text',
				style: {fill: colorList[2], font: labelFont},
				left: 'center'
			}, {
				id: 'MA30',
				type: 'text',
				style: {fill: colorList[3], font: labelFont},
				right: 0
			}, {
				id: 'High',
				type: 'text',
				style: {fill: colorList[4], font: labelFont},
				left: 'center'
			}, {
				id: 'Low',
				type: 'text',
				style: {fill: colorList[5], font: labelFont},
				right: 0
			}]
		}],
		series: [{
			name: 'Volume',
			type: 'bar',
			barWidth: '80%',
			xAxisIndex: 1,
			yAxisIndex: 1,
			itemStyle: {
				normal: {
					color: '#7fbe9e'
				},
				emphasis: {
					color: '#140'
				}
			},
			data: volumes
		}, {
			type: 'candlestick',
			name: '日K',
			barWidth: '80%',
			data: data,
			itemStyle: {
				normal: {
					color: '#ef232a',
					color0: '#14b143',
					borderColor: '#ef232a',
					borderColor0: '#14b143'
				},
				emphasis: {
					color: 'black',
					color0: '#444',
					borderColor: 'black',
					borderColor0: '#444'
				}
			}
		}, /*{
			name: 'MA5',
			type: 'line',
			data: dataMA5,
			smooth: true,
			showSymbol: false,
			lineStyle: {
				normal: {
					width: 1
				}
			}
		}, {
			name: 'MA10',
			type: 'line',
			data: dataMA10,
			smooth: true,
			showSymbol: false,
			lineStyle: {
				normal: {
					width: 1
				}
			}
		}, */{
			name: 'MA30',
			type: 'line',
			data: dataMA30,
			smooth: true,
			showSymbol: false,
			lineStyle: {
				normal: {
					width: 1,
					color: '#FFD700'
				}
			}
		}, {
			name: 'High',
			type: 'line',
			data: dataHigh,
			smooth: true,
			showSymbol: false,
			lineStyle: {
				normal: {
					width: 1,
					color: '#FF4500'
				}
			}
		}, {
			name: 'Low',
			type: 'line',
			data: dataLow,
			smooth: true,
			showSymbol: false,
			lineStyle: {
				normal: {
					width: 1,
					color: '#7CFC00'
				},
				
			}
		}]
	};
	;
	if (option && typeof option === "object") {
		myChart.setOption(option, true);
	}
}


var _sort_function = function(a, b){
	return b.new_high - a.new_high;
}

function Bar(dom, sel, stocks, out){
	
	var myChart = echarts.init(dom, null, {renderer: 'svg'});
	var app = {};
	
	stocks.sort(_sort_function)
	
	sel.sort(_sort_function)
	
	var map = {};
	var map_sel = {};
	var series_yes = [];
	var series_no = [];
	var data = [];
	
	for (var i = 0; i < stocks.length; i++){
		var e = stocks[i];
		var r = Math.round(e.new_high * 100 * 2);
		if (r >= 20) r = 20;
		if (r <= -20) r = -20;
		map[r] = map[r] || [];
		map[r].push(e);
	}
	
	for (var i = 0; i < sel.length; i++){
		var e = sel[i];
		var r = Math.round(e.new_high * 100 * 2);
		if (r >= 20) r = 20;
		if (r <= -20) r = -20;
		map_sel[r] = map_sel[r] || [];
		map_sel[r].push(e);
	}
	
	for (var i = 10; i >= -10; i -= 0.5){
		data.push(Math.round(i * 2));
	}

	for (var i = 0; i < data.length; i++){
		var arr = map[data[i]] || [];
		var arr_sel = map_sel[data[i]] || [];
		series_yes.push(arr_sel.length);
		series_no.push(arr.length - arr_sel.length);
		data[i] = (data[i] / 2);
	}
	/*
	var option = {
		xAxis: {
			type: 'category',
			data: data || ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
		},
		yAxis: {
			type: 'value'
		},
		series: [{
			data: series || [120, 200, 150, 80, 70, 110, 130],
			type: 'bar'
		}]
	};
	*/
	
	var option = {
		tooltip : {
			trigger: 'axis',
			axisPointer : {            // 坐标轴指示器，坐标轴触发有效
				type : 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
			}
		},
		legend: {
			data:['选中','未选中']
		},
		grid: {
			left: '3%',
			right: '4%',
			bottom: '3%',
			containLabel: true
		},
		xAxis : [
			{
				type : 'category',
				data : data || ['周一','周二','周三','周四','周五','周六','周日']
			}
		],
		yAxis : [
			{
				type : 'value'
			}
		],
		series : [
			{
				name: '选中',
				type: 'bar',
				stack: "股票",
				data: series_yes || [320, 332, 301, 334, 390, 330, 320]
			},
			{
				name: '未选中',
				type: 'bar',
				stack: "股票",
				data: series_no || [120, 132, 101, 134, 90, 230, 210]
			}
		]
	};

	if (option && typeof option === "object") {
		myChart.setOption(option, true);
	}
	
	return {
		map : map,
		chart: myChart
	}
}


function Index(dom, index){
	
	var myChart = echarts.init(dom, null, {renderer: 'svg'});
	
	var option = {
        legend: {},
        tooltip: {
            trigger: 'axis',
            showContent: false
        },
        dataset: {
            source: [
                ['product', '2012', '2013', '2014', '2015', '2016', '2017'],
                ['Matcha Latte', 41.1, 30.4, 65.1, 53.3, 83.8, 98.7],
                ['Milk Tea', 86.5, 92.1, 85.7, 83.1, 73.4, 55.1],
                ['Cheese Cocoa', 24.1, 67.2, 79.5, 86.4, 65.2, 82.5],
                ['Walnut Brownie', 55.2, 67.1, 69.2, 72.4, 53.9, 39.1]
            ]
        },
        xAxis: {type: 'category'},
        yAxis: {gridIndex: 0},
        grid: {top: '0%'},
        series: [
            {type: 'line', smooth: true, seriesLayoutBy: 'row'},
            {type: 'line', smooth: true, seriesLayoutBy: 'row'},
            {type: 'line', smooth: true, seriesLayoutBy: 'row'},
            {type: 'line', smooth: true, seriesLayoutBy: 'row'},
        ]
    };

    myChart.setOption(option);
}